import {
	getDocBus,
	getInfo
} from "../api/byfz";

export async function saveData() {
	let returnList = []
	let list = [];
	let list2 = [{
			value: 'shengchan',
		},
		{
			value: 'jiaohuo',
		},
		{
			value: 'caigou',
		}, {
			value: 'yangpin',
		}
	]
	const res = await getInfo();
	if (res.roles && res.roles.find(i => i == 'admin')) {
		list = list2
	}
	for (let item of res.roles) {
		if (list2.find(i => i.value == item) && !list.find(i => i.value == item)) {
			list.push(list2.find(i => i.value == item))
		}
	}
	for (let item of list) {
		try {
			const data = await getData(item.value);
			returnList = [...returnList, ...data]
		} catch (e) {

		}
	}
	let exitData = uni.getStorageSync("allData");
	if (exitData && exitData.length > 0) {
		if (exitData.length < returnList.length) {
			uni.setStorageSync("allData", returnList)
		}
	} else {
		uni.setStorageSync("allData", returnList)
	}
}
async function getData(keyWord) {
	const res = await getDocBus({
		pageNum: 1,
		pageSize: 99999999,
		tableName: keyWord,
	})
	return res.rows || []
}
// 建立一个工具类函数文件 utils.js
export function tableToExcel(jsonData) {
	//要导出的json数据
	let worksheet = 'sheet1'
	let str = '<tr><td>' + JSON.stringify(jsonData) + '</td></tr>'
	//下载的表格模板数据
	let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
      <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
      <x:Name>${worksheet}</x:Name>
      <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
      </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
      </head><body><table>${str}</table></body></html>`
	//下载模板
	return template
}
// 同上放在 utils.js
export function exportExcel(fileData, documentName = 'excel',fileType='xlsx') {
	fileData = JSON.stringify(fileData)
	/*
	PRIVATE_DOC: 应用私有文档目录常量
	PUBLIC_DOCUMENTS: 程序公用文档目录常量
	*/
	plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
		let rootObj = fs.root
		let fullPath = rootObj.fullPath
		// 创建文件夹
		rootObj.getDirectory(documentName, {
			create: true
		}, function(dirEntry) {

			// 获取当前时间
			var now = new Date();
			// 获取年份
			var year = now.getFullYear();
			// 获取月份，需要注意月份是从0开始计算的，所以需要+1
			var month = now.getMonth() + 1;
			// 获取日期
			var date = now.getDate();

			// 创建文件,防止重名
			let fileName = year + '-' + month + '-' + date
			dirEntry.getFile(`${fileName}.${fileType}`, {
				create: true
			}, function(fileEntry) {
				fileEntry.createWriter(function(writer) {
					writer.onwritestart = (e) => {
						showLoading('正在导出')
					}
					writer.onwrite = (e) => {
						// 成功导出数据
						hideLoading()
						setTimeout(() => {
							const path =
								`file://${fullPath}${documentName}/${fileName}.${fileType}`
							showToast('导出成功===地址==' + path + '==2秒后自动打开')
							console.log("path==",path)
							// 打开文件
							setTimeout(() => {
								uni.openDocument({
									filePath: path,
									success: res => {
										console.log(
											'打开文档成功',
											res)
									},
									fail: err => {
										if (err
											.errCode ==
											1 || err
											.code == 1
											) {
											uni.showToast({
												title: `未找到能打开xlsx类型文件的手机应用`,
												icon: 'none'
											})
										}
									}
								})
							}, 2000)

						}, 500)
					}
					// 写入内容
					writer.write(fileData)
				}, function(e) {
					console.log(e.message)
				})
			})
		})
	})
}

function showToast(title = '') {
	uni.hideLoading()
	uni.showToast({
		title,
		icon: 'none',
		duration: 1500
	})
}
/**
 * loading
 * @param title
 */
function showLoading(title = '加载中') {
	uni.hideLoading()
	uni.showLoading({
		title,
		mask: true
	})
}
/**
 * hideLoading
 */
function hideLoading() {
	uni.hideLoading()
}